<template>
  <div class="create-share-form">
    <div class="form-section">
      <h4>基本设置</h4>
      <div class="form-group">
        <label>分享标题</label>
        <input
          v-model="shareForm.title"
          class="form-input"
          placeholder="为您的分享起个标题..."
          type="text"
        />
      </div>

      <div class="form-group">
        <label>分享描述（可选）</label>
        <textarea
          v-model="shareForm.description"
          class="form-textarea"
          placeholder="添加描述，让其他人了解分享内容..."
          rows="3"
        ></textarea>
      </div>

      <div class="form-group">
        <label>分享类型</label>
        <div class="share-type-options">
          <label :class="{ selected: shareForm.shareType === 'public' }" class="share-type-option">
            <input
              v-model="shareForm.shareType"
              type="radio"
              value="public"
            />
            <div class="option-icon">
              <svg fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                <path d="M2 12h20" stroke="currentColor" stroke-width="2"/>
                <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" stroke="currentColor" stroke-width="2"/>
              </svg>
            </div>
            <div class="option-content">
              <div class="option-title">公开分享</div>
              <div class="option-desc">任何人都可以通过链接访问</div>
            </div>
          </label>

          <label :class="{ selected: shareForm.shareType === 'family' }" class="share-type-option">
            <input
              v-model="shareForm.shareType"
              type="radio"
              value="family"
            />
            <div class="option-icon">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" stroke="currentColor" stroke-width="2"/>
                <circle cx="12" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
              </svg>
            </div>
            <div class="option-content">
              <div class="option-title">家庭分享</div>
              <div class="option-desc">仅限家庭成员访问</div>
            </div>
          </label>

          <label :class="{ selected: shareForm.shareType === 'private' }" class="share-type-option">
            <input
              v-model="shareForm.shareType"
              type="radio"
              value="private"
            />
            <div class="option-icon">
              <svg fill="none" viewBox="0 0 24 24">
                <rect height="11" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="18" x="3" y="11"/>
                <circle cx="12" cy="16" r="1" stroke="currentColor" stroke-width="2"/>
                <path d="M7 11V7a5 5 0 0 1 10 0v4" stroke="currentColor" stroke-width="2"/>
              </svg>
            </div>
            <div class="option-content">
              <div class="option-title">私密分享</div>
              <div class="option-desc">需要密码才能访问</div>
            </div>
          </label>
        </div>
      </div>
    </div>

    <div class="form-section">
      <h4>访问控制</h4>
      <div v-if="shareForm.shareType === 'private'" class="form-group">
        <label>访问密码</label>
        <input
          v-model="shareForm.password"
          class="form-input"
          placeholder="设置访问密码"
          type="password"
        />
      </div>

      <div class="form-group">
        <label>过期时间</label>
        <div class="expire-options">
          <label :class="{ selected: shareForm.expireType === 'never' }" class="expire-option">
            <input
              v-model="shareForm.expireType"
              type="radio"
              value="never"
            />
            永不过期
          </label>
          <label :class="{ selected: shareForm.expireType === '7d' }" class="expire-option">
            <input
              v-model="shareForm.expireType"
              type="radio"
              value="7d"
            />
            7天后
          </label>
          <label :class="{ selected: shareForm.expireType === '30d' }" class="expire-option">
            <input
              v-model="shareForm.expireType"
              type="radio"
              value="30d"
            />
            30天后
          </label>
          <label :class="{ selected: shareForm.expireType === 'custom' }" class="expire-option">
            <input
              v-model="shareForm.expireType"
              type="radio"
              value="custom"
            />
            自定义
          </label>
        </div>
      </div>

      <div v-if="shareForm.expireType === 'custom'" class="form-group">
        <label>自定义过期时间</label>
        <input
          v-model="shareForm.customExpireDate"
          :min="minExpireDate"
          class="form-input"
          type="datetime-local"
        />
      </div>
    </div>

    <div class="form-section">
      <h4>权限设置</h4>
      <div class="permission-options">
        <label class="permission-option">
          <input
            v-model="shareForm.allowDownload"
            type="checkbox"
          />
          <div class="permission-content">
            <div class="permission-icon">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" stroke="currentColor" stroke-width="2"/>
              </svg>
            </div>
            <div class="permission-text">
              <div class="permission-title">允许下载</div>
              <div class="permission-desc">访客可以下载原图</div>
            </div>
          </div>
        </label>

        <label class="permission-option">
          <input
            v-model="shareForm.allowComment"
            type="checkbox"
          />
          <div class="permission-content">
            <div class="permission-icon">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" stroke="currentColor" stroke-width="2"/>
              </svg>
            </div>
            <div class="permission-text">
              <div class="permission-title">允许评论</div>
              <div class="permission-desc">访客可以留言评论</div>
            </div>
          </div>
        </label>

        <label class="permission-option">
          <input
            v-model="shareForm.allowShare"
            type="checkbox"
          />
          <div class="permission-content">
            <div class="permission-icon">
              <svg fill="none" viewBox="0 0 24 24">
                <circle cx="18" cy="5" r="3" stroke="currentColor" stroke-width="2"/>
                <circle cx="6" cy="12" r="3" stroke="currentColor" stroke-width="2"/>
                <circle cx="18" cy="19" r="3" stroke="currentColor" stroke-width="2"/>
                <line stroke="currentColor" stroke-width="2" x1="8.59" x2="15.42" y1="13.51" y2="17.49"/>
                <line stroke="currentColor" stroke-width="2" x1="15.41" x2="8.59" y1="6.51" y2="10.49"/>
              </svg>
            </div>
            <div class="permission-text">
              <div class="permission-title">允许转分享</div>
              <div class="permission-desc">访客可以分享到其他平台</div>
            </div>
          </div>
        </label>
      </div>
    </div>

    <!-- 选中的媒体文件预览 -->
    <div v-if="selectedMediaPreview.length > 0" class="form-section">
      <h4>选中的文件 ({{ selectedMediaPreview.length }})</h4>
      <div class="media-preview-grid">
        <div
          v-for="media in selectedMediaPreview"
          :key="media.id"
          class="media-preview-item"
        >
          <img
            v-if="media.thumbnail"
            :alt="media.name"
            :src="media.thumbnail"
          />
          <div v-else :class="media.type" class="file-icon">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2"/>
              <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2"/>
            </svg>
          </div>
          <div class="media-name">{{ media.name }}</div>
        </div>
      </div>
    </div>

    <!-- 社交平台分享 -->
    <div class="form-section">
      <h4>同时分享到社交平台</h4>
      <div class="social-platforms">
        <label
          v-for="platform in socialPlatforms"
          :key="platform.key"
          :class="{ selected: shareForm.socialPlatforms.includes(platform.key) }"
          class="platform-option"
        >
          <input
            v-model="shareForm.socialPlatforms"
            :value="platform.key"
            type="checkbox"
          />
          <div :class="platform.key" class="platform-icon">
            <component :is="platform.icon" />
          </div>
          <div class="platform-name">{{ platform.name }}</div>
        </label>
      </div>

      <div v-if="shareForm.socialPlatforms.length > 0" class="social-message">
        <label>分享文案</label>
        <textarea
          v-model="shareForm.socialMessage"
          class="form-textarea"
          placeholder="添加分享文案..."
          rows="2"
        ></textarea>
      </div>
    </div>

    <!-- 预览链接 -->
    <div v-if="previewUrl" class="form-section">
      <h4>分享链接预览</h4>
      <div class="preview-link">
        <div class="link-info">
          <div class="link-url">{{ previewUrl }}</div>
          <div class="link-meta">
            {{ shareForm.shareType === 'public' ? '公开' : shareForm.shareType === 'family' ? '家庭' : '私密' }} ·
            {{ shareForm.expireType === 'never' ? '永不过期' : getExpireText() }}
          </div>
        </div>
        <button class="copy-btn" @click="copyPreviewLink">
          <svg fill="none" viewBox="0 0 24 24">
            <rect height="13" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="13" x="9" y="9"/>
            <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" stroke="currentColor" stroke-width="2"/>
          </svg>
        </button>
      </div>
    </div>

    <div class="form-actions">
      <button class="btn btn-secondary" @click="$emit('cancel')">
        取消
      </button>
      <button
        :disabled="!canCreateShare"
        class="btn btn-primary"
        @click="createShare"
      >
        <svg v-if="creating" class="spinner" fill="none" viewBox="0 0 24 24">
          <circle cx="12" cy="12" fill="none" r="10" stroke="currentColor" stroke-dasharray="31.416" stroke-dashoffset="31.416" stroke-width="4"/>
        </svg>
        {{ creating ? '创建中...' : '创建分享' }}
      </button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { Message } from '@opentiny/vue'
import { createShareLink } from '@/api/share'

interface Props {
  selectedMedia: any[]
}

const props = defineProps<Props>()
const emit = defineEmits(['created', 'cancel'])

const creating = ref(false)
const previewUrl = ref('')

// 表单数据
const shareForm = reactive({
  title: '',
  description: '',
  shareType: 'family' as 'public' | 'family' | 'private',
  password: '',
  expireType: 'never' as 'never' | '7d' | '30d' | 'custom',
  customExpireDate: '',
  allowDownload: true,
  allowComment: true,
  allowShare: false,
  socialPlatforms: [] as string[],
  socialMessage: ''
})

// 社交平台配置
const socialPlatforms = [
  { key: 'wechat', name: '微信', icon: 'IconWechat' },
  { key: 'weibo', name: '微博', icon: 'IconWeibo' },
  { key: 'qq', name: 'QQ空间', icon: 'IconQQ' },
  { key: 'douyin', name: '抖音', icon: 'IconDouyin' }
]

// 计算属性
const selectedMediaPreview = computed(() => {
  return props.selectedMedia.slice(0, 6) // 最多显示6个预览
})

const minExpireDate = computed(() => {
  const tomorrow = new Date()
  tomorrow.setDate(tomorrow.getDate() + 1)
  return tomorrow.toISOString().slice(0, 16)
})

const canCreateShare = computed(() => {
  if (!shareForm.title.trim()) return false
  if (shareForm.shareType === 'private' && !shareForm.password.trim()) return false
  if (shareForm.expireType === 'custom' && !shareForm.customExpireDate) return false
  return true
})

const getExpireText = () => {
  switch (shareForm.expireType) {
    case '7d':
      return '7天后过期'
    case '30d':
      return '30天后过期'
    case 'custom':
      return shareForm.customExpireDate ?
        new Date(shareForm.customExpireDate).toLocaleDateString() + '过期' :
        '自定义过期'
    default:
      return '永不过期'
  }
}

// 监听表单变化，生成预览链接
watch(shareForm, () => {
  if (shareForm.title.trim()) {
    const params = new URLSearchParams()
    params.set('type', shareForm.shareType)
    params.set('title', shareForm.title)
    previewUrl.value = `https://family.app/share/${generateShareId()}?${params.toString()}`
  } else {
    previewUrl.value = ''
  }
}, { deep: true })

const generateShareId = () => {
  return Math.random().toString(36).substr(2, 9)
}

const copyPreviewLink = async () => {
  try {
    await navigator.clipboard.writeText(previewUrl.value)
    Message.success('链接已复制到剪贴板')
  } catch (error) {
    Message.error('复制失败')
  }
}

const createShare = async () => {
  if (!canCreateShare.value) return

  creating.value = true

  try {
    let expireTime
    if (shareForm.expireType === '7d') {
      expireTime = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()
    } else if (shareForm.expireType === '30d') {
      expireTime = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
    } else if (shareForm.expireType === 'custom') {
      expireTime = shareForm.customExpireDate
    }

    const response = await createShareLink({
      mediaIds: props.selectedMedia.map(m => m.id),
      shareType: shareForm.shareType,
      expireTime,
      password: shareForm.shareType === 'private' ? shareForm.password : undefined,
      allowDownload: shareForm.allowDownload,
      allowComment: shareForm.allowComment
    })

    if (response.code === 200) {
      emit('created', response.data)
      Message.success('分享链接创建成功')

      // 如果选择了社交平台，进行社交分享
      if (shareForm.socialPlatforms.length > 0) {
        // 这里可以调用社交分享API
        console.log('社交平台分享:', shareForm.socialPlatforms, shareForm.socialMessage)
      }
    }
  } catch (error) {
    console.error('创建分享失败:', error)
    Message.error('创建分享失败')
  } finally {
    creating.value = false
  }
}

// 初始化表单
if (props.selectedMedia.length > 0) {
  shareForm.title = props.selectedMedia.length === 1 ?
    props.selectedMedia[0].name :
    `${props.selectedMedia.length} 个文件的分享`
}
</script>

<style lang="scss" scoped>
.create-share-form {
  display: flex;
  flex-direction: column;
  gap: 2rem;

  .form-section {
    h4 {
      font-size: 1rem;
      font-weight: 600;
      color: #1e293b;
      margin: 0 0 1rem 0;
    }

    .form-group {
      margin-bottom: 1.5rem;

      label {
        display: block;
        font-weight: 500;
        color: #374151;
        margin-bottom: 0.5rem;
        font-size: 0.9rem;
      }

      .form-input,
      .form-textarea {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        font-size: 0.9rem;
        transition: border-color 0.2s ease;

        &:focus {
          outline: none;
          border-color: #3b82f6;
        }

        &::placeholder {
          color: #9ca3af;
        }
      }

      .form-textarea {
        resize: vertical;
        min-height: 80px;
      }
    }
  }

  .share-type-options {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;

    .share-type-option {
      display: flex;
      align-items: center;
      gap: 1rem;
      padding: 1rem;
      border: 2px solid #e5e7eb;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        border-color: #d1d5db;
        background: #f9fafb;
      }

      &.selected {
        border-color: #3b82f6;
        background: rgba(59, 130, 246, 0.05);
      }

      input[type="radio"] {
        display: none;
      }

      .option-icon {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f3f4f6;
        border-radius: 8px;
        flex-shrink: 0;

        svg {
          width: 20px;
          height: 20px;
          color: #6b7280;
        }
      }

      .option-content {
        flex: 1;

        .option-title {
          font-weight: 500;
          color: #1e293b;
          margin-bottom: 0.25rem;
        }

        .option-desc {
          font-size: 0.85rem;
          color: #64748b;
        }
      }

      &.selected .option-icon {
        background: rgba(59, 130, 246, 0.1);

        svg {
          color: #3b82f6;
        }
      }
    }
  }

  .expire-options {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 0.75rem;

    .expire-option {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0.75rem;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      cursor: pointer;
      font-size: 0.9rem;
      font-weight: 500;
      color: #374151;
      transition: all 0.2s ease;

      &:hover {
        border-color: #d1d5db;
        background: #f9fafb;
      }

      &.selected {
        border-color: #3b82f6;
        background: rgba(59, 130, 246, 0.05);
        color: #3b82f6;
      }

      input[type="radio"] {
        display: none;
      }
    }
  }

  .permission-options {
    display: flex;
    flex-direction: column;
    gap: 1rem;

    .permission-option {
      display: flex;
      align-items: center;
      gap: 1rem;
      padding: 1rem;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        background: #f9fafb;
      }

      input[type="checkbox"] {
        width: 20px;
        height: 20px;
        accent-color: #3b82f6;
      }

      .permission-content {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        flex: 1;

        .permission-icon {
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f3f4f6;
          border-radius: 6px;

          svg {
            width: 16px;
            height: 16px;
            color: #6b7280;
          }
        }

        .permission-text {
          .permission-title {
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 0.25rem;
          }

          .permission-desc {
            font-size: 0.8rem;
            color: #64748b;
          }
        }
      }
    }
  }

  .media-preview-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 0.75rem;

    .media-preview-item {
      text-align: center;

      img {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
      }

      .file-icon {
        width: 80px;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f3f4f6;
        border: 1px solid #e5e7eb;
        border-radius: 6px;

        svg {
          width: 24px;
          height: 24px;
          color: #6b7280;
        }

        &.video {
          background: rgba(239, 68, 68, 0.1);
          svg { color: #ef4444; }
        }

        &.audio {
          background: rgba(16, 185, 129, 0.1);
          svg { color: #10b981; }
        }
      }

      .media-name {
        font-size: 0.75rem;
        color: #64748b;
        margin-top: 0.5rem;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .social-platforms {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 0.75rem;
    margin-bottom: 1rem;

    .platform-option {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 0.5rem;
      padding: 1rem;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        border-color: #d1d5db;
        background: #f9fafb;
      }

      &.selected {
        border-color: #3b82f6;
        background: rgba(59, 130, 246, 0.05);
      }

      input[type="checkbox"] {
        display: none;
      }

      .platform-icon {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;

        &.wechat { background: #07c160; color: white; }
        &.weibo { background: #ff8200; color: white; }
        &.qq { background: #12b7f5; color: white; }
        &.douyin { background: #fe2c55; color: white; }
      }

      .platform-name {
        font-size: 0.8rem;
        font-weight: 500;
        color: #374151;
      }
    }
  }

  .social-message {
    .form-textarea {
      min-height: 60px;
    }
  }

  .preview-link {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;

    .link-info {
      flex: 1;
      min-width: 0;

      .link-url {
        font-family: 'Monaco', 'Courier New', monospace;
        font-size: 0.85rem;
        color: #3b82f6;
        margin-bottom: 0.25rem;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .link-meta {
        font-size: 0.8rem;
        color: #64748b;
      }
    }

    .copy-btn {
      width: 36px;
      height: 36px;
      background: #3b82f6;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;

      &:hover {
        background: #2563eb;
      }

      svg {
        width: 16px;
        height: 16px;
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #e5e7eb;

    .btn {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.75rem 1.5rem;
      border-radius: 8px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }

      .spinner {
        width: 16px;
        height: 16px;
        animation: spin 1s linear infinite;
      }

      &.btn-secondary {
        background: #f1f5f9;
        color: #64748b;
        border: 1px solid #e2e8f0;

        &:hover:not(:disabled) {
          background: #e2e8f0;
        }
      }

      &.btn-primary {
        background: #3b82f6;
        color: white;
        border: 1px solid #3b82f6;

        &:hover:not(:disabled) {
          background: #2563eb;
        }
      }
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .create-share-form {
    .share-type-options .share-type-option {
      flex-direction: column;
      text-align: center;
      gap: 0.75rem;
    }

    .expire-options {
      grid-template-columns: repeat(2, 1fr);
    }

    .social-platforms {
      grid-template-columns: repeat(2, 1fr);
    }

    .form-actions {
      flex-direction: column;

      .btn {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>
